<?php
declare (strict_types=1);

namespace app\store\model\job;

use app\common\model\job\Job as JobModel;
use app\store\model\student\User;
use app\store\model\UploadFile as UploadFileModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\db\exception\DbException;
use think\Paginator;

class Job extends JobModel
{
    /**
     * 获取用户列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);

        $order = [
            'create_time' => 'desc',
        ];
        if (!empty($param['create_time']) && is_array($param['create_time'])) {
            $times = between_time($param['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        } else if (!empty($param['create_time'])) {
            $order['create_time'] = $param['create_time'];
        }

        if (!empty($param['update_time']) && is_array($param['update_time'])) {
            $times = between_time($param['update_time']);
            $filter[] = ['update_time', '>=', $times['start_time']];
            $filter[] = ['update_time', '<', $times['end_time'] + 86400];
        } else if (!empty($param['update_time'])) {
            $order['update_time'] = $param['update_time'];
        }


        // 查询列表记录
        $list = $query
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order($order)
            ->paginate($param['pageSize'] ?? 10);
        return $list;
    }

    public function searchAll($param = [])
    {
// 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);
        // 查询列表记录
        $list = $query
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['job_id' => 'asc'])
            ->select();
        return $list;
    }

    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'job_name' => '',
            'status' => '',
        ]);

        $filter = [];
        !empty($params['job_name']) && $filter[] = ["job_name", "like", "%{$params['job_name']}%"];
        $params['status'] !== '' && $filter[] = ['status', '=', $params['status']];
        return $filter;
    }

    /**
     * 增加记录
     * @param array $data
     * @return bool
     */
    public function add($data)
    {
        if (self::checkJobNameExist($data['job_name'])) {
            $this->error = $data['job_name'] . '已存在，请换一个重试！';
            return false;
        }
        $data['store_id'] = self::$storeId;
        return $this->save($data);
    }

    public function importExcelFile($file_id, $store_user)
    {
        $fileInfo = UploadFileModel::detail((int)$file_id);
        $filePath = ROOT_PATH() . '/public/uploads/' . $fileInfo->file_path;
        $spreadsheet = IOFactory::load($filePath);
        $list = $spreadsheet->getActiveSheet()->toArray();
        $error = "";
        $addData = [];
        foreach ($list as $index => $item) {
            if ($index > 0) {
                $data = [
                    'status' => 0,
                    'is_delete' => 0,
                    'create_time' => time(),
                    'store_id' => self::$storeId,
                ];
                $hanshu = $index + 1;
                // 姓名
                if ($item[1]) {
                    $data["job_name"] = trim((string)$item[1]);
                } else {
                    $error = "第{$hanshu}行错误：岗位不能为空！";
                    break;
                }
                $data["remark"]='';
                if ($item[2]) {
                    $data["remark"] = trim((string)$item[2]);
                }

                $job = $this->where([
                    'job_name' => $data["job_name"],
                    'is_delete' => 0
                ])->find();
                if ($job) {
                    $error = "第{$hanshu}行错误：【{$data["job_name"]}】已存在记录，请勿重复导入！";
                    break;
                }
                $addData[] = $data;
            }
        }
        if ($error) {
            $this->error = $error;
            return false;
        }
        return $this->insertAll($addData) ? count($addData) : false;
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data)
    {
        if ($data['job_name'] != $this->job_name && self::checkJobNameExist($data['job_name'])) {
            $this->error = $data['job_name'] . '已存在，请换一个重试！';
            return false;
        }
        return $this->save($data);
    }


    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }


}
